package com.youth.oauth.config.security;

import cn.hutool.json.JSONUtil;
import com.youth.oauth.commons.beans.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理RESTful API认证失败的组件
 * 该类实现了AuthenticationFailureHandler接口，用于自定义认证失败时的处理逻辑
 */
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * 处理认证失败的逻辑
     * 当用户认证失败时，此方法将被调用，它负责向响应中写入错误信息
     *
     * @param request  HTTP请求对象，包含请求相关信息
     * @param response HTTP响应对象，用于向客户端发送响应
     * @param exception 认证失败异常，包含认证失败的原因
     * @throws IOException 如果在写入响应时发生I/O错误
     * @throws ServletException 如果处理认证失败时发生错误
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应的字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        // 设置响应的内容类型为application/json
        response.setContentType("application/json");
        // 创建一个表示认证错误的结果对象
        Result result = Result.error("用户未认证失败");
        // 将结果对象转换为JSON字符串
        String json = JSONUtil.toJsonStr(result);
        // 将JSON字符串写入响应中
        response.getWriter().write(json);
    }
}

